import { Effect } from 'dva';
import { Reducer } from 'redux';
import { Subscription } from 'umi';

export enum CloseType {
    line = "line",
    card = "card",
    EditableCard = "editable-card",
}

export interface TabModel {
    name?: string,
    tabKey?: string,
    path?: string,
    state?: any,
}

export interface TabModelState {
    currentKey: string;
    tabList: TabModel[];
    curTab: TabModel;
    closeType: CloseType;
}

export interface TabModelType {
    namespace: 'common';
    state: TabModelState;
    effects: {
        ChangeTabsEffect: Effect;
        ReduceTabEffect: Effect;
    };
    subscriptions: {
        setup: Subscription
    },
    reducers: {
        addTab: Reducer;
        resetTab: Reducer;
        setNewTab: Reducer;
    };
}

// @ts-ignore
// @ts-ignore
// @ts-ignore
const CommonModule: TabModelType = {
    namespace: 'common',
    state: {
        currentKey: '',
        tabList: [],
        curTab: {},
        closeType: CloseType.card,
    },
    // state:{},
    reducers: {
        addTab(state, { payload }) {
            const { tabList } = state;

            if (payload.isTopMenu) {
                const pos = tabList.findIndex((_tab: any) => _tab.name === payload.name);
                if (pos !== -1) {
                    tabList[pos] = payload;
                } else {
                    tabList.push({
                        name: payload.name,
                        path: payload.path,
                        state: payload?.state
                    });
                }
            } else {
                const pos = tabList.findIndex((_tab: any) => _tab.path === payload.path && _tab.name === payload.name);
                if (pos === -1) {
                    const { pathname, search } = window.location;
                    const currentPos = tabList.findIndex((_tab: any) => _tab.path === pathname + search);
                    tabList.splice(currentPos + 1, 0, payload);
                }
            }

            return {
                ...state,
                tabList,
            };
        },
        setNewTab: (state, { payload }) => {
            return {
                ...state,
                curTab: payload.curTab,
            };
        },
        resetTab(state, { payload }) {
            return {
                ...state,
                tabList: payload.tabList,
            };
        },
    }


};

export default CommonModule;
